package com.estore.view;

import com.estore.model.Product;
import com.estore.service.ProductService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * 控制台商城界面
 * 提供用户交互界面和购物功能
 */
public class ConsoleShop {

    private final ProductService productService = new ProductService();
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);
    private double totalSpent = 0.0; // 累计消费金额

    /**
     * 启动商城系统
     */
    public void start() {
        System.out.println("🚀 正在启动商城系统...");
        showWelcomeMessage();

        while (true) {
            showMainMenu();
            int choice = getIntInput("请输入您的选择: ");
            scanner.nextLine(); // 消费掉换行符

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    searchProducts();
                    break;
                case 3:
                    addToCart();
                    break;
                case 4:
                    viewCart();
                    break;
                case 5:
                    updateCart();
                    break;
                case 6:
                    checkout();
                    break;
                case 7:
                    viewProductDetails();
                    break;
                case 8:
                    viewStatistics();
                    break;
                case 9:
                    showOrderHistory();
                    break;
                case 0:
                    System.out.println("感谢使用我们的商城，期待再次光临！");
                    return;
                default:
                    System.out.println("❌ 无效的选项，请重新输入！");
            }

            pressAnyKeyToContinue();
        }
    }

    /**
     * 显示欢迎信息
     */
    private void showWelcomeMessage() {
        System.out.println("\n" +
                "⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️\n" +
                "⭐️                                        ⭐️\n" +
                "⭐️        欢迎来到 Java 电子商城          ⭐️\n" +
                "⭐️                                        ⭐️\n" +
                "⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️\n");
    }

    /**
     * 显示主菜单
     */
    private void showMainMenu() {
        System.out.println("\n📋 === 主菜单 ===");
        System.out.println("1. 📦 浏览所有商品");
        System.out.println("2. 🔍 搜索商品");
        System.out.println("3. 🛒 添加商品到购物车");
        System.out.println("4. 🧾 查看购物车");
        System.out.println("5. ✏️  修改购物车");
        System.out.println("6. 💰 结算订单");
        System.out.println("7. 📄 查看商品详情");
        System.out.println("8. 📊 查看商城统计");
        System.out.println("9. 📜 查看订单历史");
        System.out.println("0. ❌ 退出系统");
        System.out.println("⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️");
    }

    /**
     * 浏览所有商品
     */
    private void browseProducts() {
        System.out.println("\n📦 === 商品列表 ===");
        List<Product> products = productService.getAllProducts();

        if (products.isEmpty()) {
            System.out.println("😔 商店里还没有商品。");
            return;
        }

        System.out.printf("%-6s %-20s %-10s %-8s %s\n",
                "ID", "商品名称", "价格", "库存", "状态");
        System.out.println("------------------------------------------------------------");

        for (int i = 0; i < products.size(); i++) {
            Product product = products.get(i);
            String status = product.isInStock() ? "有货" : "缺货";
            String statusIcon = product.isInStock() ? "✅" : "❌";
            System.out.printf("%-6s %-20s ¥%-9.2f %-8d %s %s\n",
                    product.getId(),
                    truncateString(product.getName(), 18),
                    product.getPrice(),
                    product.getStock(),
                    statusIcon,
                    status);
        }

        System.out.println("------------------------------------------------------------");
        System.out.println("✅ 有货  ❌ 缺货");
    }

    /**
     * 搜索商品
     */
    private void searchProducts() {
        System.out.print("\n🔍 请输入搜索关键词: ");
        String keyword = scanner.nextLine().trim();

        if (keyword.isEmpty()) {
            System.out.println("❌ 搜索关键词不能为空！");
            return;
        }

        List<Product> results = productService.searchProductsByName(keyword);

        System.out.println("\n📋 === 搜索结果 ===");
        if (results.isEmpty()) {
            System.out.println("😔 没有找到包含 '" + keyword + "' 的商品。");
            return;
        }

        System.out.printf("%-6s %-20s %-10s %-8s %s\n",
                "ID", "商品名称", "价格", "库存", "状态");
        System.out.println("------------------------------------------------------------");

        for (Product product : results) {
            String statusIcon = product.isInStock() ? "✅" : "❌";
            String status = product.isInStock() ? "有货" : "缺货";
            System.out.printf("%-6s %-20s ¥%-9.2f %-8d %s %s\n",
                    product.getId(),
                    truncateString(product.getName(), 18),
                    product.getPrice(),
                    product.getStock(),
                    statusIcon,
                    status);
        }
    }

    /**
     * 添加商品到购物车
     */
    private void addToCart() {
        System.out.println("\n🛒 === 添加商品到购物车 ===");
        System.out.print("请输入商品ID: ");
        String productId = scanner.nextLine().trim().toLowerCase();

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.println("❌ 错误：找不到该商品！");
            return;
        }

        if (!product.isInStock()) {
            System.out.println("😔 抱歉，该商品已售罄。");
            return;
        }

        System.out.println("📄 商品信息: " + product.getName() + " | 价格: ¥" + product.getPrice() + " | 库存: " + product.getStock());

        int quantity = getIntInput("请输入购买数量: ");
        if (quantity <= 0) {
            System.out.println("❌ 错误：购买数量必须为正数！");
            return;
        }

        if (!productService.isStockSufficient(productId, quantity)) {
            System.out.println("❌ 错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        int currentQuantity = shoppingCart.getOrDefault(productId, 0);
        shoppingCart.put(productId, currentQuantity + quantity);

        double itemTotal = product.getPrice() * quantity;
        System.out.println("✅ 成功将 '" + product.getName() + "' × " + quantity + " 添加到购物车！");
        System.out.println("💰 小计: ¥" + String.format("%.2f", itemTotal));
    }

    /**
     * 查看购物车
     */
    private void viewCart() {
        System.out.println("\n🧾 === 我的购物车 ===");
        if (shoppingCart.isEmpty()) {
            System.out.println("😔 购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        int totalItems = 0;

        System.out.printf("%-20s %-10s %-8s %-12s %s\n",
                "商品名称", "单价", "数量", "小计", "状态");
        System.out.println("----------------------------------------------------------------");

        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);

            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                String status = productService.isStockSufficient(productId, quantity) ? "✅ 充足" : "❌ 不足";

                System.out.printf("%-20s ¥%-9.2f %-8d ¥%-11.2f %s\n",
                        truncateString(product.getName(), 18),
                        product.getPrice(),
                        quantity,
                        subtotal,
                        status);

                total += subtotal;
                totalItems += quantity;
            }
        }

        System.out.println("----------------------------------------------------------------");
        System.out.printf("📦 商品种类: %d 种 | 🎯 商品数量: %d 件\n", shoppingCart.size(), totalItems);
        System.out.printf("💰 订单总计: ¥%.2f\n", total);

        // 显示操作提示
        System.out.println("\n💡 提示: 选择菜单选项 5 修改购物车，选项 6 进行结算");
    }

    /**
     * 修改购物车
     */
    private void updateCart() {
        if (shoppingCart.isEmpty()) {
            System.out.println("😔 购物车是空的，无需修改。");
            return;
        }

        viewCart();
        System.out.print("\n✏️  请输入要修改的商品ID: ");
        String productId = scanner.nextLine().trim().toLowerCase();

        if (!shoppingCart.containsKey(productId)) {
            System.out.println("❌ 错误：购物车中没有该商品！");
            return;
        }

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.println("❌ 错误：商品不存在！");
            shoppingCart.remove(productId);
            return;
        }

        System.out.println("当前数量: " + shoppingCart.get(productId));
        System.out.println("1. 修改数量");
        System.out.println("2. 移除商品");
        System.out.println("3. 取消");

        int choice = getIntInput("请选择操作: ");
        switch (choice) {
            case 1:
                int newQuantity = getIntInput("请输入新的数量: ");
                if (newQuantity <= 0) {
                    shoppingCart.remove(productId);
                    System.out.println("✅ 已从购物车移除 '" + product.getName() + "'");
                } else if (productService.isStockSufficient(productId, newQuantity)) {
                    shoppingCart.put(productId, newQuantity);
                    System.out.println("✅ 已更新 '" + product.getName() + "' 数量为 " + newQuantity);
                } else {
                    System.out.println("❌ 错误：库存不足！当前库存为 " + product.getStock());
                }
                break;
            case 2:
                shoppingCart.remove(productId);
                System.out.println("✅ 已从购物车移除 '" + product.getName() + "'");
                break;
            case 3:
                System.out.println("取消修改。");
                break;
            default:
                System.out.println("❌ 无效的选择！");
        }
    }

    /**
     * 结算订单
     */
    private void checkout() {
        if (shoppingCart.isEmpty()) {
            System.out.println("😔 购物车是空的，无法结算。");
            return;
        }

        System.out.println("\n💰 === 订单结算 ===");
        viewCart();

        // 检查库存是否充足
        boolean allInStock = true;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            if (!productService.isStockSufficient(entry.getKey(), entry.getValue())) {
                allInStock = false;
                Product product = productService.findProductById(entry.getKey());
                System.out.println("❌ '" + product.getName() + "' 库存不足！");
            }
        }

        if (!allInStock) {
            System.out.println("❌ 部分商品库存不足，请修改购物车后重新结算。");
            return;
        }

        // 计算总金额
        double total = calculateCartTotal();
        System.out.printf("\n💰 订单总金额: ¥%.2f\n", total);

        System.out.print("确认结算订单吗？(y/N): ");
        String confirm = scanner.nextLine().trim();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            // 减少库存
            for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
                productService.decreaseStock(entry.getKey(), entry.getValue());
            }

            totalSpent += total;
            System.out.println("🎉 订单结算成功！感谢您的购买！");
            System.out.println("💰 本次消费: ¥" + String.format("%.2f", total));
            System.out.println("💰 累计消费: ¥" + String.format("%.2f", totalSpent));

            // 清空购物车
            shoppingCart.clear();
        } else {
            System.out.println("取消结算。");
        }
    }

    /**
     * 查看商品详情
     */
    private void viewProductDetails() {
        System.out.print("\n📄 请输入商品ID查看详情: ");
        String productId = scanner.nextLine().trim().toLowerCase();

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.println("❌ 错误：找不到该商品！");
            return;
        }

        System.out.println("\n📄 === 商品详情 ===");
        System.out.println(product.toDetailedString());
    }

    /**
     * 查看商城统计
     */
    private void viewStatistics() {
        System.out.println("\n📊 === 商城统计 ===");
        System.out.println(productService.getStatistics());
        System.out.printf("💰 您的累计消费: ¥%.2f\n", totalSpent);
        System.out.println("🛒 当前购物车商品数: " + shoppingCart.size() + " 种");
    }

    /**
     * 查看订单历史
     */
    private void showOrderHistory() {
        System.out.println("\n📜 === 消费记录 ===");
        System.out.printf("💰 累计消费金额: ¥%.2f\n", totalSpent);
        if (totalSpent > 0) {
            System.out.println("🎉 感谢您一直以来的支持！");
        } else {
            System.out.println("😊 您还没有消费记录，快去选购商品吧！");
        }
    }

    /**
     * 计算购物车总金额
     */
    private double calculateCartTotal() {
        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            Product product = productService.findProductById(entry.getKey());
            if (product != null) {
                total += product.getPrice() * entry.getValue();
            }
        }
        return total;
    }

    /**
     * 获取整数输入
     */
    private int getIntInput(String prompt) {
        while (true) {
            System.out.print(prompt);
            if (scanner.hasNextInt()) {
                return scanner.nextInt();
            } else {
                System.out.println("❌ 请输入有效的数字！");
                scanner.next(); // 清除无效输入
            }
        }
    }

    /**
     * 截断字符串
     */
    private String truncateString(String str, int length) {
        if (str.length() <= length) {
            return str;
        }
        return str.substring(0, length - 3) + "...";
    }

    /**
     * 按任意键继续
     */
    private void pressAnyKeyToContinue() {
        System.out.print("\n⏎ 按回车键继续...");
        scanner.nextLine();
    }

    public static void main(String[] args) {
        ConsoleShop shop = new ConsoleShop();
        shop.start();
    }
}